// src/utils/crypto.js
/**
 * 加解密工具类
 * 提供Base64编码和解码功能，兼容所有平台
 */

/**
 * Base64编码方法
 * @param {string} str - 要编码的字符串
 * @returns {string} 编码后的Base64字符串
 */
export const base64Encode = (str) => {
  // 使用自定义base64编码，兼容所有平台
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  let output = '';
  const bytes = [];

  // 将字符串转换为字节数组
  for (let i = 0; i < str.length; i++) {
    bytes.push(str.charCodeAt(i));
  }

  // 每3个字节编码为4个base64字符
  for (let i = 0; i < bytes.length; i += 3) {
    const byte1 = bytes[i];
    const byte2 = i + 1 < bytes.length ? bytes[i + 1] : 0;
    const byte3 = i + 2 < bytes.length ? bytes[i + 2] : 0;

    const enc1 = byte1 >> 2;
    const enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);
    const enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
    const enc4 = byte3 & 63;

    output += chars[enc1] + chars[enc2] + (i + 1 < bytes.length ? chars[enc3] : '=') + (i + 2 < bytes.length ? chars[enc4] : '=');
  }

  return output;
};

/**
 * Base64解码方法
 * @param {string} str - 要解码的Base64字符串
 * @returns {string} 解码后的原始字符串
 */
export const base64Decode = (str) => {
  // 使用自定义base64解码，兼容所有平台
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  let output = '';
  const bytes = [];

  // 移除填充字符
  str = str.replace(/=+$/, '');

  // 将base64字符串转换为字节数组
  for (let i = 0; i < str.length; i += 4) {
    const enc1 = chars.indexOf(str[i]);
    const enc2 = chars.indexOf(str[i + 1]);
    const enc3 = chars.indexOf(str[i + 2]);
    const enc4 = chars.indexOf(str[i + 3]);

    const byte1 = (enc1 << 2) | (enc2 >> 4);
    const byte2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    const byte3 = ((enc3 & 3) << 6) | enc4;

    bytes.push(byte1);
    if (enc3 !== -1) bytes.push(byte2);
    if (enc4 !== -1) bytes.push(byte3);
  }

  // 将字节数组转换为字符串
  for (let i = 0; i < bytes.length; i++) {
    output += String.fromCharCode(bytes[i]);
  }

  return output;
};

/**
 * 生成支付二维码地址
 * @param {string} userId - 用户ID
 * @param {number|string} amount - 支付金额
 * @returns {string} 编码后的支付地址
 */
export const generatePaymentAddress = (userId, amount = '') => {
  const originalAddress = `nexabank_payment_qrcode:${userId}:${amount}`;
  return base64Encode(originalAddress);
};

/**
 * 解析支付二维码地址
 * @param {string} encodedAddress - 编码后的支付地址
 * @returns {object} 解析结果 { valid: boolean, userId: string, amount: string, original: string }
 */
export const parsePaymentAddress = (encodedAddress) => {
  try {
    const decoded = base64Decode(encodedAddress);

    if (decoded.startsWith('nexabank_payment_qrcode:')) {
      const parts = decoded.split(':');
      const userId = parts[1] || '';
      const amount = parts[2] || '';
      return {
        valid: true,
        userId,
        amount,
        original: decoded
      };
    } else {
      return {
        valid: false,
        userId: '',
        amount: '',
        original: decoded
      };
    }
  } catch (error) {
    console.error('解析支付地址失败:', error);
    return {
      valid: false,
      userId: '',
      amount: '',
      original: ''
    };
  }
};
